﻿<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FormacaoVaga.ascx.cs" Inherits="RzCorportativo.Views.FormacaoVaga" %>
<div class="span15 well">
    <div class="controls controls-row">
        <asp:TextBox runat="server" ID="NomeCurso" placeholder="Curso" type="text" name="complete"
            value="" auto-complete="true" eid="descricaoNomeCurso" requesttype="post" contenttype="application/json; charset=utf-8"
            isasync="true" length="1" datatype="json" templeted="true" onrender="getItemFormacao"
            onerror="getErrorFormacao" onselected="selectedItemFormacao" data-toggle="tooltip" title="Curso"
            data-placement="left" />
        <asp:HiddenField runat="server" ID="FormacaoId" />
        <asp:HiddenField runat="server" ID="CursoId" />
    </div>
    <div class="controls controls-row">
        <asp:Button Text="adicionar" runat="server" CssClass="btn btn-success" ID="btnAdionaFormacao" />
    </div>
</div>
<br />
<div dataspy="">
    <table class="table table-hover" id="gridFormacao" runat="server">
        <thead>
            <tr>
                <th>
                    CURSO
                </th>
                <th>#</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
<%--<script src="<%=this.ResolveUrl("~/Recursos/j/Formacao.js")%>" type="text/javascript"></script>--%>
<script type="text/javascript">

    function Formacao() {
        this.FormacaoId = 0;
        this.CursoId = 0;
        this.EnderecoId = 0;
        this.Instituicao = "";
        this.AnoInicio = 0;
        this.AnoFim = 0;
        this.Endereco = {
            EnderecoId: 0,
            Logradouro: "",
            Numero: "",
            Cep: "",
            CidadeId: 0
        };
        this.Usuario = {
        }
        this.UsuarioId = 0;
        this.Concluido = false;
        this.IsNew = true;

        this.Deletar = function (control, vagaId) {
            var vagaId = vagaId || $("input[id$='VagaId']").val();
            var json = JSON.stringify(this);
            var alerta = new Alert();
            alerta.Name = "erroGeral";
            if (alerta.HasMessage()) {
                alerta.Type = AlertType.Error;
                alerta.Show();
                return;
            }
            var current = this;
            json = '{ "formacaoId" : ' + current.FormacaoId.toString(10) + ', vagaId: ' + vagaId +'}';
            $.ajax({
                url: eS.UrlPadrao + 'Views/Cadastros/Vaga.aspx/RemoveFormacao',
                type: "post",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: json,
                success: function (e) {
                    if (e.d && e.d.AlertType != undefined) {
                        $(control).parent().parent().remove();
                        alerta.Type = e.d.AlertType;
                        for (var i in e.d.Messages) {
                            alerta.AddMessage(e.d.Messages[i]);
                        }
                        if (e.d.Show && e.d.Show == true) {
                            alerta.Show();
                        }
                    } else {
                        if (e.responseText) {
                            alerta.Type = 2;
                            alerta.AddMessage(e.responseText);
                        } else {
                            alerta.Type = 1;
                            alerta.AddMessage("Retorno inválido, o objeto retornado não está em um formato correto")
                        }
                        alerta.Show();
                    }

                },
                error: function (e) {
                    alerta.Type = 1;
                    alerta.AddMessage(e.responseText);
                    alerta.Show();
                }
            });

        }

        this.Salvar = function () {
            var vagaId = $("input[id$='VagaId']").val();
            var json = JSON.stringify(this);
            var alerta = new Alert();
            alerta.Name = "erroGeral";
            if (vagaId == "" || isNaN(vagaId)) {
                alerta.AddMessage("Vaga inválida");

            }
            if (alerta.HasMessage()) {
                alerta.Type = AlertType.Error;
                alerta.Show();
                return;
            }
            var current = this;
            json = '{ "formacao" : ' + json + ', vagaId: ' + vagaId + '}';
            $.ajax({
                url: eS.UrlPadrao + 'Views/Cadastros/Vaga.aspx/AddFormacao',
                type: "post",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: json,
                success: function (e) {
                    if (e.d && e.d.AlertType != undefined) {
                        current.FormacaoId = e.d.Value;
                        //$("tr[formacao='" + current.FormacaoId + "']:first").remove();
                        alerta.Type = e.d.AlertType;
                        for (var i in e.d.Messages) {
                            alerta.AddMessage(e.d.Messages[i]);
                        }
                        if (e.d.Show && e.d.Show == true) {
                            alerta.Show();
                        }
                        var idUsuario = usuarioId;
                        var concluidoText = current.AnoFim == 0 ? "" : "CONCLUÍDO";

                        var tbody = "<tr formacao='" + current.CursoId + "'><td>" + $("input[id$='NomeCurso']").val() + "</td><td><input type='button' id='btnRemove'" + current.CursoId.toString(10) +
                         " onclick='RemoveFormacao(" + current.CursoId + ", " + vagaId + ", this)' class='btn btn-danger' value='remover'/></td></tr>";


                        $('table[id$="gridFormacao"] tr:last').after(tbody);
                        $("input[id$='NomeCurso']").val("");
                    } else {
                        if (e.responseText) {
                            alerta.Type = 2;
                            alerta.AddMessage(e.responseText);
                        } else {
                            alerta.Type = 1;
                            alerta.AddMessage("Retorno inválido, o objeto retornado não está em um formato correto")
                        }
                        alerta.Show();
                    }

                },
                error: function (e) {
                    alerta.Type = 1;
                    alerta.AddMessage(e.responseText);
                    alerta.Show();
                }
            });
        }
        return this;
    }
    Formacao.Options = {
        DefaultSelector: ''
    }
    $(function () {
        Formacao.Options.DefaultSelector = "MainContent_CursoCurriculo_Endereco_";
        $("input[id$='btnAdionaFormacao']").click(function (e) {
            e.preventDefault();
            var formacao = new Formacao();
            formacao.FormacaoId = parseInt($("input[id$='FormacaoId']").val(), 10);
            formacao.FormacaoId = isNaN(formacao.FormacaoId) ? 0 : formacao.FormacaoId;

            formacao.CursoId = parseInt($("input[id$='CursoId']").val(), 10);
            formacao.CursoId = isNaN(formacao.CursoId) ? 0 : formacao.CursoId;


            var alerta = new Alert();
            alerta.Name = "erroGeral";
            if ($("input[id$='VagaId']").val().length == "" || isNaN(parseInt($("input[id$='VagaId']").val(), 10))) {
                alerta.AddMessage("Vaga inválida, selecione ou cadastre  uma vaga para associar a formação!");
            }
            if (formacao.CursoId == 0) {
                alerta.AddMessage("Curso inválido");
            }
            if (isNaN(formacao.FormacaoId) && $("input[id$='FormacaoId']").val().length > 0) {
                alerta.AddMessage("Selecione uma formação válido");
            }
            if ($("input[id$='VagaId']").val().length == 0 || isNaN($("input[id$='VagaId']").val())) {
                alerta.AddMessage("Vaga inválida");
            }
            if (alerta.HasMessage()) {
                alerta.Type = AlertType.Error;
                alerta.Show();
            }
            else
                formacao.Salvar();
            return false;
        });
    });

    function RemoveFormacao(formacaoId, vagaId, control) {
        var formacao = new Formacao();
        formacao.FormacaoId = formacaoId;
        formacao.Deletar(control);
    }

    function getItemFormacao(ul, item) {

        var inner_html = '<a><div class="list_item_container"><div class=""><strong>Curso:</strong> ' +
                            item.Nome + '</div></div></a>';
        return $("<li style='width:350px'></li>")
            .data("item.autocomplete", item)
            .append(inner_html)
            .appendTo(ul);
    }

    function getErrorFormacao(e) {
        var _alert = new Alert();
        _alert.Name = "erroGeral";
        _alert.Type = AlertType.Error;
        _alert.AddMessage(e.d ? e.d : e.responseText);
        _alert.Show();
    }

    function selectedItemFormacao(event, ui, context) {
        var item = ui.item && ui.item.value ? ui.item : context;
        if (item.CursoId) {
            $("input[id$='CursoId']").val(item.CursoId.toString(10))
        }
    }


</script>
